package ssq.gamest.port.android;

import ssq.gamest.R;
import ssq.gamest.webserver.HttpWebServer;
import ssq.gamest.webserver.WebServer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class HTTPService extends Service
{
    private static final int    NOTIFICATION_STARTED_ID = 1;
    
    private NotificationManager notifyManager           = null;
    private Thread              createServerThread      = null;
    public WebServer            server;
    
    @Override
    public void onCreate()
    {
        super.onCreate();
        notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        
        createServerThread = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    HTTPService.this.server = HttpWebServer.runAndGetServer(new String[] { "-p", String.valueOf(App.getWebServerPort()), "-P", String.valueOf(App.getWsServerPort()) });
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }
    
    @Override
    public void onDestroy()
    {
        if (server != null)
            server.stopThread();
        notifyManager.cancel(NOTIFICATION_STARTED_ID);
        notifyManager = null;
        super.onDestroy();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        createServerThread.start();
        showNotification();
        return START_STICKY;
    }
    
    @Override
    public boolean onUnbind(Intent intent)
    {
        return super.onUnbind(intent);
        
    }
    
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
    
    private void showNotification()
    {
        String text = "Gamest 服务器正在运行...";
        Notification notification = new Notification(R.drawable.favicon, text, System.currentTimeMillis());
        Intent startIntent = new Intent(this, MainActivity.class);
        startIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(this, 0, startIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
        notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
        notification.setLatestEventInfo(this,
                "Gamest安卓游戏平台",
                "Gamest正在运行",
                intent);
        notifyManager.notify(NOTIFICATION_STARTED_ID, notification);
    }
}
